package com.ita.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.ita.annotation.ControllerLog;
import com.ita.dto.OrderDto;
import com.ita.pojo.MUser;
import com.ita.pojo.Order;
import com.ita.service.OrderService;
import com.ita.util.Constant;
import com.ita.util.JacksonUtil;
import com.ita.vo.JsonResult;

@RestController
@RequestMapping("api/order")
@CrossOrigin
public class APIOrderController {

	@Resource(name = "orderService")
	private OrderService oService;

	@RequestMapping(value = "/add", method = RequestMethod.PUT)
	@ControllerLog(description = "add order")
	public @ResponseBody JsonResult add(@RequestBody OrderDto orderDto) {
		JsonResult result = new JsonResult();
		Order order = null;
		try {
			order = oService.addOrder(orderDto);
			if (order == null) {
				result.setCode(Constant.FAIL);
			} else {
				result.setCode(Constant.SUCCESS);
				TextMessage message = new TextMessage(Constant.ORDERCOMING);
				MyWsHandler.sendMessage(orderDto.getM_id(), message);
			}
		} catch (Exception e) {
			result.setCode(Constant.FAIL);
			result.setMsg("Service Exception");
			return result;
		}

		return result;

	}

	@RequestMapping(value = "/{oid}/affirm/{affirm}", method = RequestMethod.PATCH)
	@ControllerLog(description = "affirm the order state")
	public JsonResult affirm(@PathVariable("oid") String oid, @PathVariable("affirm") int affirm) {
		System.out.println(oid);
		System.out.println(affirm);

		JsonResult result = new JsonResult();
		int update = 0;

		try {
			update = oService.updateState(oid, affirm);
		} catch (Exception e) {
			result.setCode(Constant.FAIL);
			result.setMsg("Service Exception");
			return result;
		}

		if (update == 1) {
			result.setCode(Constant.SUCCESS);
			result.setData(oid);
		} else {
			result.setCode(Constant.FAIL);
		}

		String string = JacksonUtil.getJsonFromObject(result);
		System.out.println(string);

		return result;
	}

}
